import { _decorator, Component, director, Node, TextAsset, Vec3 } from 'cc';
import { BoardData, GameData } from '../Data/GameData';
import { UserData } from '../Data/UserData';
import InitData from '../game/InitData';
import { AudioMgr } from '../Mgr/AudioMgr';
import { BoardMgr } from '../Mgr/BoardMgr';
import { UIMgr } from '../Mgr/UIMgr';
import { NCPoint } from '../src/api/api.config.client';
import { ClientAPI } from '../src/api/client.api';
import ServiceAPI from '../src/api/service.api';
import { Popup } from '../src/ui/page/popup';
import I18n, { CountryType } from '../Tools/i18n/I18n';
import { Url } from '../Tools/Url';
const { ccclass, property } = _decorator;

@ccclass('GameMgr')

export class GameMgr extends Component {

    /** 单例模式 */
    private static _ins: GameMgr;
    constructor() {
        super();
        GameMgr._ins = this;
    }
    public static get ins(): GameMgr {
        if (!GameMgr._ins) {
            GameMgr._ins = new GameMgr();
        }
        return GameMgr._ins;
    }

    /** 棋盘数据text */
    @property(TextAsset)
    private boardConfig: TextAsset = null;
    /** 词库3数据text */
    @property(TextAsset)
    private word3Config: TextAsset = null;
    /** 词库4数据text */
    @property(TextAsset)
    private word4Config: TextAsset = null;
    /** 词库5数据text */
    @property(TextAsset)
    private word5Config: TextAsset = null;
    /** 词库6数据text */
    @property(TextAsset)
    private word6Config: TextAsset = null;

    @property(Node)
    guide: Node = null;
    private lastReturnedIndex: number = 0;

    usePropTimes: number = 1;

    public isPassLevel: boolean = false;
    public isUseProp: boolean = false;


    private timeoutId: any = null;

    private readonly delay = 5000; // 7秒的延迟

    start() {
        //  埋点
        if (!GameData.data.gameInitFinish) {
            GameData.data.gameInitFinish = 1;
            ClientAPI.Point(NCPoint.GAMEINITFINISH, { userid: UserData.data.userId ?? -99 });
            ClientAPI.Point(NCPoint.GAMESTART, { userid: UserData.data.userId ?? -99 });
        }

        AudioMgr.ins.play(Url.AUDIO.BGM);
        // console.log('当前关卡', UserData.data.curLevel);
        this.gameStart();

        ServiceAPI.onException(async () => {
            let network = await ClientAPI.Network();
            if (!network) {
                await Popup.Exceptionpage();
            }
            return [network, network ? 3 : Infinity];
        });
    }

    update(deltaTime: number) {

    }

    loadScene() {
        director.loadScene('test')
    }

    /** 加载解码地图json配置 */
    loadTextConfig(): Promise<void> {
        return new Promise((resolve, reject) => {
            try {
                // 解析boardConfig
                let boardcontext = this.boardConfig.text.decodeAtoB;
                GameData.data.boardJson = mtec.parseJson(boardcontext);
                // 解析word3Config
                let word3context = this.word3Config.text.decodeAtoB;
                GameData.data.word3Json = mtec.parseJson(word3context);
                // 解析word4Config
                let word4context = this.word4Config.text.decodeAtoB;
                GameData.data.word4Json = mtec.parseJson(word4context);
                // 解析word5Config
                let word5context = this.word5Config.text.decodeAtoB;
                GameData.data.word5Json = mtec.parseJson(word5context);
                // 解析word6Config
                let word6context = this.word6Config.text.decodeAtoB;
                GameData.data.word6Json = mtec.parseJson(word6context);
                resolve();
            } catch (error) {
                // 如果解析出错，reject Promise
                reject(error);
            }
        });
    }


    public async gameStart() {
        //解析地图和单词资源
        this.loadTextConfig()
            .then(() => {
                GameData.data.boardData = new BoardData(GameData.data.boardJson);//Test模式下注释掉
                // console.log(GameData.data.boardData.type1Data); // 打印 Type_1 中的所有二维数组
                // console.log(GameData.data.boardData.type2Data); // 打印 Type_2 中的所有二维数组
                // console.log(GameData.data.boardData.type3Data); // 打印 Type_3 中的所有二维数组
                // console.log(GameData.data.boardData.type4Data); // 打印 Type_4 中的所有二维数组
                // console.log(GameData.data.boardData.type5Data); // 打印 Type_5 中的所有二维数组
                // console.log('Board-Data: All-->', GameData.data.boardData);
                BoardMgr.ins.gameBoardInit()
            })
        // console.log(UserData.data.isCommer, UserData.data.guideRecord);
        if (UserData.data.isCommer != false) {
            // console.log("开启新手引导");
            UserData.data.guideRecord = 1;
            UserData.data.isCommer = true;
            this.guide.active = true;
        } else {
            // UserData.data.isCommer = false;
            this.guide.active = false;
        }

        // Tools.delay(0.5, () => BoardMgr.ins.gameBoardInit());
    }

    public passLevel() {
        if (UserData.data.curLevel == 7) {
            console.log('评分弹窗');
            ClientAPI.ScorePop()
        }
        this.getElimitateCash();
        UIMgr.ins.playBoardAnim();
        AudioMgr.ins.playOneShot(Url.AUDIO.SFX6, 1);
        UserData.data.passLevelTimes++;//  过关次数+1
        UserData.data.tempPassLevelTimes_lottery++;//   临时过关次数+1
        UserData.data.curLevel++;//  关卡+1
        this.isUseProp = false;
        BoardMgr.ins.level1WordsIndex = 0;
        BoardMgr.ins.level1ReverseIndex = 0;
        GameMgr.ins.usePropTimes = 1;//道具次数刷新
        BoardMgr.ins.drawLineTimes = 0;//   连词次数清零
        BoardMgr.ins.clearBoardWord();//    清空棋盘
        BoardMgr.ins.clearBoardLineColor();//   清空棋盘颜色
        BoardMgr.ins.gameBoardInit();//     初始化棋盘信息
        UIMgr.ins.updateCondLabel('', '#FFFFFF');//    更新提示词
        UIMgr.ins.updateContainerLevelString();//   更新关卡展示
        UIMgr.ins.updateLotteryProgress();//    更新抽奖进度条
        UIMgr.ins.freshLightState();//  刷新道具按钮状态
        BoardMgr.ins.currentGraphicsIndex = 7;
        BoardMgr.ins.showOneAnswerFristWordTimes = 0;
        InitData.getWithdrawConf(true);

    }

    public gameOver() {

    }

    public reStartGame() {
        this.startTimer();
        AudioMgr.ins.playOneShot(Url.AUDIO.SFX9, 1);
        this.isPassLevel = false;
        this.isUseProp = false;
        BoardMgr.ins.level1WordsIndex = 0;
        BoardMgr.ins.level1ReverseIndex = 0;
        GameMgr.ins.usePropTimes = 1;//道具次数刷新
        BoardMgr.ins.drawLineTimes = 0;//   连词次数清零
        BoardMgr.ins.clearBoardWord();//    清空棋盘
        BoardMgr.ins.clearBoardLineColor();//   清空棋盘颜色
        BoardMgr.ins.gameBoardInit();//     初始化棋盘信息
        UIMgr.ins.updateCondLabel('', '#FFFFFF');//    更新提示词
        UIMgr.ins.freshLightState();//  刷新道具按钮状态
        BoardMgr.ins.currentGraphicsIndex = 7;
        BoardMgr.ins.showOneAnswerFristWordTimes = 0;
    }

    public startTimer() {
        if (UserData.data.isCommer) {
            return
        }
        // 确保没有已有的定时器
        if (this.timeoutId === null) {
            this.timeoutId = setTimeout(() => {
                if (!GameMgr.ins.isPassLevel || GameMgr.ins.isUseProp) {
                    BoardMgr.ins.showOneAnswerFristWord(); // 5秒后执行
                }
                this.resetTimer(); // 执行完后重置计时器
            }, this.delay);
        }
    }

    public resetTimer() {
        // 取消已有定时器
        if (this.timeoutId !== null) {
            clearTimeout(this.timeoutId);
            this.timeoutId = null;
        }
    }

    // [
    //     { "redStartCount": 0, "redEndCount": 20, "forcePopIntervalList": [ 5, 5 ] },
    //     { "redStartCount": 21, "redEndCount": 80, "forcePopIntervalList": [ 5, 4 ] },
    //     { "redStartCount": 81, "redEndCount": 150, "forcePopIntervalList": [ 4, 3 ] },
    //     { "redStartCount": 151, "redEndCount": 100000, "forcePopIntervalList": [ 3, 3 ] }
    // ]




    private __elimit_cash_cache__: ReturnType<typeof ServiceAPI.EliminateReport>;
    /** 每次消除获取奖励 */
    public async getElimitateCash(_nodepos?: Vec3, isPass = false) {
        InitData.checkUserInfo();
        // let prms = this.__elimit_cash_cache__;
        let prms = this.__elimit_cash_cache__ ?? ServiceAPI.EliminateReport(UserData.data.userId);
        console.log('是否过关：', isPass);
        if (!isPass) {
            this.__elimit_cash_cache__ = ServiceAPI.EliminateReport(UserData.data.userId);
        }
        // 立即处理奖励展示
        if (_nodepos) {
            let start_date = new Date();
            try {
                const res = await prms;
                console.log('消除奖励；', res);
                if (res && res.cashTotal !== undefined) {
                    // 立即展示效果
                    UIMgr.ins.shwoGetCashEffect(_nodepos);
                    UIMgr.ins.updateCashLabel(Math.max(UserData.data.curCashTotal, res.cashTotal), res.cashAmount);
                } else {
                    console.warn('EliminateReport 返回了无效值:', res);
                }
            } catch (error) {
                console.log('消除奖励---请求失败:', Date.now() - start_date.valueOf(), error);
            }
        }
    }
    /**
     * 获取交替返回的 forcePopIntervalList 的值
     * @param dataList - 包含 redStartCount, redEndCount, 和 forcePopIntervalList 的数据数组
     * @param redPacket - UserData.data.redPacket 的值
     * @returns forcePopIntervalList 中交替返回的值，或 undefined 如果没有找到匹配的区间
     */
    public getNextIntervalValue(): boolean {
        let luckyWardNorgetTimes = UserData.data.luckyWardNorgetTimes;
        let dataList = GameData.data.forceConfig;
        if (!dataList) {
            ServiceAPI.ConfCommon(UserData.data.userId)
                .then(ConfCommon => {
                    UserData.data.passLevelTimes = ConfCommon?.eliminateTotal;
                    UserData.data.drawTotal = ConfCommon?.drawTotal;
                    GameData.data.forceConfig = ConfCommon?.forceConfig;
                    GameData.data.drawProcessConfig = ConfCommon?.drawProcessConfig;
                });
            return void 0;
        }
        let redPacket = UserData.data.redPacket;
        // 找到 redPacket 所属的区间
        let matchingData = dataList.find(data => redPacket >= data.redStartCount && redPacket <= data.redEndCount);

        if (!matchingData) {
            matchingData = dataList.lastElement;
        }

        if (matchingData) {
            // 获取 forcePopIntervalList 数组
            const intervalList = matchingData.forcePopIntervalList;

            // 根据 lastReturnedIndex 交替返回数组中的值
            const valueToReturn = intervalList[this.lastReturnedIndex];
            if (luckyWardNorgetTimes >= valueToReturn) {
                // 更新 lastReturnedIndex，为下次调用做准备
                this.lastReturnedIndex = (this.lastReturnedIndex + 1) % intervalList.length;
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 检测邮箱或手机号是否符合规则
     * @param input 
     * @returns 
     */
    // public determineInputType(input: string): "EMAIL" | "PHONE" | boolean {
    //     // 邮箱的正则表达式
    //     const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    //     // 电话号码的正则表达式（简单格式验证数字和可选的前导+号）
    //     const phonePattern = /^\+?\d{10,15}$/;

    //     // 定义每个国家对应的电话号码规则
    //     const countryPhoneRules: { [key in CountryType]?: RegExp } = {
    //         [CountryType.BR]: /^\d{10,11}$/, // Type_02
    //         [CountryType.US]: /^\d{10}$/,    // Type_03
    //         [CountryType.GB]: /^\d{10,11}$/, // Type_02
    //         [CountryType.CA]: /^\d{10}$/,    // Type_03
    //         [CountryType.AU]: /^\d{9}$/,     // Type_04
    //         [CountryType.JP]: /^\d{10,11}$/, // Type_02
    //         [CountryType.KR]: /^\d{7,9}$/,   // Type_05
    //         [CountryType.DE]: /^\d{8}$/,     // Type_06
    //         [CountryType.FR]: /^\d{10}$/     // Type_03
    //     };

    //     // 判断是否是邮箱
    //     if (emailPattern.test(input)) {
    //         return "EMAIL";
    //     }

    //     // 判断是否是电话号码
    //     else if (phonePattern.test(input)) {
    //         const curCountry = I18n.curCountry; // 获取当前国家代码

    //         if (curCountry && countryPhoneRules[curCountry]) {
    //             const rule = countryPhoneRules[curCountry];

    //             // 先尝试匹配带区号的号码
    //             const withoutCountryCode = input.replace(/^\+?\d{1,4}/, ''); // 去掉可能存在的区号

    //             if (rule.test(withoutCountryCode)) {
    //                 return "PHONE";
    //             } else if (rule.test(input)) {
    //                 return "PHONE";
    //             } else {
    //                 return false; // 电话号码不符合当前国家的规则
    //             }
    //         }
    //         return "PHONE"; // 默认返回 PHONE
    //     } else {
    //         return false; // 输入既不是有效的邮箱也不是有效的电话号码
    //     }
    // }

}


